package com.mistermind;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MisterMind extends Activity {
	private EditText input;
	private TextView feedback;
	private Button button;
	private List<Integer> answer;
	private Integer tries;
	private boolean flag;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initGame();
    }
    private void initGame(){
    	input = (EditText)findViewById(R.id.insertfield);
    	feedback = (TextView)findViewById(R.id.feedback);
    	button = (Button)findViewById(R.id.checkbutton);
    	generateAnswer();
    	flag = true;
    	button.setText("Check Answer");
    	input.setEnabled(true);
    	button.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ checkans(); }});
    }
	private void generateAnswer() {
		feedback.setText("");
		input.setText("");
		answer = new ArrayList<Integer>();
		for(int i = 0 ; i<4; i++){
			answer.add((int)(Math.random()*10));
		}
		tries = 0;
	}
	protected void checkans() {
		int wrong=0,regular=0,ok=0;
		feedback.setText("");
		String rta = input.getText().toString();
		List<Integer> rtaList = new ArrayList<Integer>();
		for(Character c: rta.toCharArray()){
			if(Character.isDigit(c))
				rtaList.add(c-'0');
			else{
				flag = false;
				feedback.setText("All the characters must be digits");
				return;
			}
		}
		if(rtaList.size() != answer.size()){
			feedback.setText("You have to insert 4 numbers");
			return;
		}
		tries++;
		flag = true;
		for(int i=0; i<rtaList.size() ; i++){
			if(rtaList.get(i).equals(answer.get(i))){
				ok++;
			} else if(answer.contains(rtaList.get(i))) {
				regular++;
			} else {
				wrong++;
			}
		}
		flag = (ok==answer.size());
		String show = "";
		if(ok>0){
			show += "Correct: "+ok;
		}
		if(regular>0){
			if(show.length() > 4){
				show+="\n";
			}
			show += "Regular: "+regular;
		}
		if(wrong>0){
			if(show.length() > 4){
				show+="\n";
			}
			show += "Wrong: "+wrong;
		}
		feedback.setText(show);
		if(flag){
			endGame();
		}
	}
	
	private void endGame() {
		input.setEnabled(false);
		feedback.setText("You've won!!! After "+(tries-1)+" tries");
		button.setText("New Game");
		button.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ initGame(); }});
	}
}
